package pl.itconsus.model.entities.utils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Enumeration;

import javax.persistence.Transient;

import org.apache.commons.collections.BeanMap;

import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;

public abstract class BaseEntity<ID> implements Serializable {


	/**
	 * 
	 */
	private static final long serialVersionUID = -7581537741661533003L;

	/**
	 * field should be marked as transient in superclass
	 * 
	 * @return id field for entity
	 * @see Transient
	 */
	public abstract ID getId();

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		BeanMap beanMap = new BeanMap(this);
		ToStringHelper tsh = Objects.toStringHelper(this.getClass());
		for (Object key : beanMap.keySet()) {
			Object value = beanMap.get(key);
			if (key instanceof String) {
				if (value instanceof Enumeration<?>) {
					tsh.add((String) key, "ItemsCount["
							+ ((Collection<?>) value).size() + "]");
				} else {
					tsh.add((String) key, value);
				}
			}
		}
		return tsh.toString();
	}

	/**
	 * Generic equal for entities with Id
	 */
	@Override
	public boolean equals(Object obj) {
		if (this.getId() != null && obj instanceof BaseEntity) {
			@SuppressWarnings("unchecked")
			BaseEntity<ID> be = (BaseEntity<ID>) obj;
			return this.getId().equals(be.getId());
		}
		return super.equals(obj);
	}

	/**
	 * Generic hasCode for entities with Id
	 */
	@Override
	public int hashCode() {
		return Objects.hashCode(this.getClass(), this.getId());
	}

}
